package com.um.jdy.tcp.netty;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.tcp.cmd.CommandLogs;
import com.um.jdy.tcp.cmd.CommandReceiver;
import com.um.jdy.tcp.cmd.SDKCommand;
import com.um.jdy.tcp.cmd.SDKCommandParser;
import com.um.jdy.tcp.properties.HshNettyProperties;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;


/**
 * 业务处理类
 *
 * @author 邓南辉
 * @date 2020/3/5
 * @copyright 广州优匠科技有限公司
 */
@Slf4j
@Component
public class SDKCommandHandler {

    @Autowired
    protected CommandLogs commandLogs;

    @Autowired
    protected SDKCommandParser sdkCommandParser;

    @Autowired
    protected CommandReceiver commandReceiver;

    @Autowired
    HshNettyProperties hshNettyProperties;

    protected void handleCommand(String command, ChannelHandlerContext ctx) {
        SDKCommand cmd = sdkCommandParser.parse(command);
        log.debug("收到命令：{}", cmd);
        if (cmd == null || StrUtil.isBlank(cmd.getDevice()))
            return;

        ChannelHandlerContext lastContext = NettyContextHolder.putDeviceContext(cmd.getDevice(), ctx);
        if (!Objects.equals(lastContext, ctx)) {
            NettyChannelAttrs.setDeviceName(ctx, cmd.getDevice());
            log.info("设备上线[{}]：{} {}", cmd.getDevice(), ctx.channel().remoteAddress(), ctx.channel().id());
        }

        Date time = DateUtil.date();
        commandReceiver.receiver(cmd.getDevice(), cmd, time);
        commandLogs.addLogs(cmd.getDevice(), command, time,true);
    }

    /**
     * 设备离线通知
     *
     * @param imei
     */
    protected void deviceOffline(String imei, ChannelHandlerContext ctx) {
        if (StrUtil.isNotBlank(imei)) {
            log.info("设备离线[{}]：{} {}", imei, ctx.channel().remoteAddress(), ctx.channel().id());
            commandReceiver.offline(imei);
        }
    }
}
